package com.zdp.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * @Author zhengdp
 * @Description
 */
public class AsyncTimeServerHandler implements Runnable {
    private int port;

    CountDownLatch latch;

    AsynchronousServerSocketChannel asynchronousServerSocketChannel;


    public AsyncTimeServerHandler(int port) {
        this.port = port;
        try {
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            // 开始监听 accept 事件
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time Server is start in port: " + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            // 防止服务端执行完成后退出，因为我们是新起了一个线程来处理连接
            // 事件的处理是异步的
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept() {
        // 接受请求并处理，传递到 AcceptCompletionHandler 中进行处理
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }
}
